#-*-coding:utf-8-*-
import base64
import os
import random

from PIL import Image
import io
import mdl_formal
# import mdl_t
import numpy as np

sys_random = random.SystemRandom()
# np.set_printoptions(threshold=np.NaN)

class NonceSource:
    def __init__(self, root):
        self.interesting_filenames = os.listdir(root)
        self.interesting_images = []
        for name in self.interesting_filenames:
            if not name.startswith('.') and name != 'Thumbs.db':
                self.interesting_images.append(Image.open(os.path.join(root,name)))


    # def provide_image(self, limit=10, width=80, height=80):
    #     for i in range(0,limit):
    #         image = sys_random.choice(self.interesting_images)
    #         image = image.resize((width,height))
    #         image = image.convert('L')
    #         mat = np.array(image)
    #         (flag, img, mdl) = mdl_formal.overseg(mat)
    #
    #         if flag == True:
    #             break
    #
    #     img = img.convert("RGB")
    #
    #     #
    #     # img.save(buffer, format="PNG")
    #     # with open(buffer, 'rb') as f:
    #     #     str = base64.b64encode(f.read())
    #     # print(type(str))
    #     #
    #
    #     return img
    #     # return str
    #
    # def provide_nonce(self, limit=10, width=80, height=80):
    #     buffer = cStringIO.StringIO()
    #     img = self.provide_image(limit, width, height)
    #     img.save(buffer, format="PNG")
    #     return buffer.getvalue()

    def provide_image(self, limit=10, width=80, height=80):
        while True:
            image = sys_random.choice(self.interesting_images)
            # image.show()
            image = image.resize((width, height), Image.ANTIALIAS)
            image = image.convert('L')
            image.show()
            mat = np.array(image)
            # (flag, img, mdl_value, boundaries, ori_grey, best_seg) = mdl_formal.overseg(mat)
            (flag, img, mdl_value) = mdl_formal.overseg(mat)
            img.show()

            if flag == True:
                break

        sum = 0
        for i in np.array(img):
            for j in i:
                sum += j
        nonce = sum * mdl_value
        nonce_int = int(nonce)

        #
        # img.save(buffer, format="PNG")
        # with open(buffer, 'rb') as f:
        #     str = base64.b64encode(f.read())
        # print(type(str))
        #

        # return (img, mdl_value, boundaries, ori_grey, best_seg)
        img = img.convert("RGB")
        return nonce_int, img

    def provide_nonce(self, limit=10, width=80, height=80):
        # buffer = io.StringIO()
        nonce_int, img = self.provide_image(limit, width, height)
        # img.save(buffer, format="PNG")
        img_str = to_str(img)
        return nonce_int, img_str
        # return nonce_int, buffer.getvalue()
        # return (img, buffer.getvalue())
        # return img

def to_str(bytes_or_str):
    if isinstance(bytes_or_str, bytes):
        value = bytes_or_str.decode('utf-8')
    else:
        value = bytes_or_str
    return value  # Instance of str

if __name__=="__main__":
    import encode
    # print "Nonce: " + encode.encode(NonceSource('/Users/jerryin/Desktop/pic/').provide_nonce())
    nonce_int, img = NonceSource('/Users/jerryin/Desktop/pic/').provide_nonce()
    print(nonce_int)
    print(img)
    # sum = 0
    # for i in np.array(img):
    #     for j in i:
    #         sum += j
    # print(sum * mdl_value)
    # a.save(buffer, format="PNG")
    # b = buffer.getvalue()
    # b = encode.encode(b)
    # print 'Nonce: ' + b
    # c = a.convert('L')
    # c = np.array(c)
    # print c